package com.ljh.SimpleTradingSystem.controller;

import com.ljh.SimpleTradingSystem.mybatis.entity.Goods;
import com.ljh.SimpleTradingSystem.mybatis.entity.UserCollection;
import com.ljh.SimpleTradingSystem.mybatis.mapper.GoodsMapper;
import com.ljh.SimpleTradingSystem.mybatis.mapper.UserCollectionMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class GoodsListController {
    @Resource
    GoodsMapper goodsMapper;

    @Resource
    UserCollectionMapper userCollectionMapper;

    @Resource
    HttpServletRequest req;

    final int pageSize = 8;

    @GetMapping("/goodslist")
    public String getGoodsList() {
        return "GoodsList";
    }

    @GetMapping("/goodslist/pagenum")
    @ResponseBody
    public String getPageNum() {
        int pageNum = goodsMapper.countAll();
        if (pageNum % pageSize == 0) pageNum = pageNum / pageSize;
        else pageNum = pageNum / pageSize + 1;
        return String.valueOf(pageNum);
    }

    @PostMapping("/goodslist")
    @ResponseBody
    public List<Goods> getGoods(@RequestParam int page) {
        List<Goods> goodsList = goodsMapper.selectByPage((page - 1) * pageSize, pageSize);
        return goodsList;
    }

    @GetMapping("/detail/{id}/{type}")
    public String getDetail(Model model, @PathVariable String id, @PathVariable int type) {
        model.addAttribute("goodsId", id);
        if (type == 1) return "Detail"; //type为1返回商品详情视图
        return "Auction"; //否则返回拍卖视图
    }

    @PostMapping("/detail/{id}")
    @ResponseBody
    public Goods getGoodsById(@PathVariable String id) {
        Goods goods = goodsMapper.selectById(Integer.parseInt(id));
        return goods;
    }

    @GetMapping("/search/pagenum")
    @ResponseBody
    public String getPageNumBySearch(@RequestParam String column, @RequestParam String value) {
        int pageNum = goodsMapper.countAllByColumn(column, value);
        if (pageNum % pageSize == 0) pageNum = pageNum / pageSize;
        else pageNum = pageNum / pageSize + 1;
        return String.valueOf(pageNum);
    }

    @PostMapping("/search")
    @ResponseBody
    public List<Goods> search(@RequestParam String column, @RequestParam String value, @RequestParam int page) {
        List<Goods> goodsList = goodsMapper.selectByColumn(column, value, (page - 1) * pageSize, pageSize);
        return goodsList;
    }

    @GetMapping("/order")
    @ResponseBody
    public List<Goods> orderByColumn(@RequestParam String column, @RequestParam String rule, @RequestParam int page) {
        List<Goods> goodsList = goodsMapper.orderByColumn(column, rule, (page - 1) * pageSize, pageSize);
        return goodsList;
    }

    @GetMapping("/thumb")
    @ResponseBody
    public String getThumbNum(@RequestParam int id) {
        Goods goods = goodsMapper.selectById(id);
        return String.valueOf(goods.getThumbNum());
    }

    @PostMapping("/thumb")
    public void thumb(@RequestParam int id, @RequestParam int num) {
        goodsMapper.updateThumbNumById(id, num);
    }

    @GetMapping("/comment/num")
    @ResponseBody
    public String getCommentNum(@RequestParam int id) {
        Goods goods = goodsMapper.selectById(id);
        return String.valueOf(goods.getCommentNum());
    }

    @PostMapping("/comment/num")
    public void addCommentNum(@RequestParam int id, @RequestParam int num) {
        goodsMapper.updateCommentNumById(id, num);
    }

    @GetMapping("/release")
    public String release() {
        String userId = String.valueOf(req.getSession().getAttribute("userId"));
        if (!userId.equals("null")) {
            return "Release";
        } else {
            return "Login";
        }
    }

    @PostMapping("/subscribe")
    @ResponseBody
    public String subscribe(@RequestParam int id) {
        HttpSession session = req.getSession();
        int userId = Integer.parseInt(String.valueOf(session.getAttribute("userId")));
        UserCollection collection = userCollectionMapper.selectByUserIdAndGoodsId(userId, id);
        if (collection == null) {
            userCollectionMapper.insert(new UserCollection(id, userId));
            return "关注成功";
        } else {
            return "无法重复关注该商品";
        }
    }

    private String getImagePath(MultipartFile file) {
        //保存文件到本地
        String uploadPath = "c:/upload";
        File folder = new File(uploadPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        String originalFileName = file.getOriginalFilename();
        //执行保存文件
        File dest = new File(folder, originalFileName);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "http://localhost:8080/" + originalFileName;
    }

    @PostMapping("/add")
    public String add(@RequestParam String name, @RequestParam String introduction,
                      @RequestParam double price, @RequestParam String type,
                      @RequestParam("file") MultipartFile file) {
        String imagePath = getImagePath(file);

        HttpSession session = req.getSession();
        int merchantId = Integer.parseInt(String.valueOf(session.getAttribute("userId")));

        Date time = new Date();
        String releaseTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time);

        Goods goods = new Goods(merchantId, name, type, releaseTime, price, 0, 0, introduction, imagePath);
        goodsMapper.insert(goods);
        return "GoodsList";
    }

    @GetMapping("/mysell")
    public String getSell() {
        return "SellList";
    }

    @PostMapping("/mysell")
    @ResponseBody
    public List<Goods> getSellList() {
        HttpSession session = req.getSession();
        int merchantId = Integer.parseInt(String.valueOf(session.getAttribute("userId")));
        List<Goods> goodsList = goodsMapper.selectByMerchantId(merchantId);
        return goodsList;
    }

    @GetMapping("/mycollection")
    public String getCollection() {
        return "Collection";
    }

    @PostMapping("/mycollection")
    @ResponseBody
    public List<Goods> getCollectionList() {
        HttpSession session = req.getSession();
        int userId = Integer.parseInt(String.valueOf(session.getAttribute("userId")));
        List<UserCollection> collectionList = userCollectionMapper.selectByUserId(userId);
        List<Goods> goodsList = new ArrayList<>();
        for (int i = 0; i < collectionList.size(); ++i) {
            int goodsId = collectionList.get(i).getGoodsId();
            Goods goods = goodsMapper.selectById(goodsId);
            goodsList.add(goods);
        }
        return goodsList;
    }

    @GetMapping("/cancelsub/{id}")
    public String cancelSub(@PathVariable String id) {
        HttpSession session = req.getSession();
        int userId = Integer.parseInt(String.valueOf(session.getAttribute("userId")));
        userCollectionMapper.deleteByUserIdAndGoodsId(userId, Integer.parseInt(id));
        return "Collection";
    }

    @GetMapping("/auction/{id}")
    public String getAuction(Model model, @PathVariable String id) {
        model.addAttribute("goodsId", id);
        return "Auction";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable String id) {
        goodsMapper.deleteById(Integer.parseInt(id));
        return "SellList";
    }
}
